<?php


class Vote extends A_Content {
	private $_results = null;
	private $_filter="";
		
	public function add() {
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."vote(status_id) values(0)");
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}

	public function getById($id) {//взять конкретный опрос по идешнику
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleVote($this->_top, $this, $id);
		}
		
		return $this->_cashe_obj[$id];
	}

	public function length() { //кол-во опросов
        $get_data = $this->_top->_sql->exe("SELECT count(*) as c FROM ".TAB_PREF."vote c ".$this->_filter);
		return $get_data[0]['c'];
	}	

	public function Make(){
		$get_result = $this->_top->_sql->exe("SELECT vote_id FROM ".TAB_PREF."vote c ".$this->_filter);
		$this->_results = array();
		for ($r=0;$r<count($get_result);$r++) {
			array_push($this->_results, $get_result[$r]['vote_id']); 
		}	   
	}	

	//возвращает случайный опрос (фильтр учитывается)
	public function random(){
		if ($this->_results===null) {
			$this->Make();
		}
				
		$rand_id = array_rand($this->_results, 1);
		
		return $this->getById($this->_results[$rand_id]);
	}
	
	public function item($idx) {	   
		if ($this->_results===null) {
			$this->Make();
		}
		return $this->getById($this->_results[$idx]);
	}

    public function limitActiveOnly(){//тольк активные
        $this->_filter = "where status_id= 1";
    }

    public function resetActiveOnly(){//тольк активные
        $this->_filter = "";
    }
}


class SingleVote extends A_SingleContent {
	protected $_cashe_obj = array();
	protected $_results = null;	
	
	protected function loader() {
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."vote WHERE vote_id={$this->_content_id}");
		if (count($get_data)==0) {
			throw $this->_top->Utils->PushError('Vote object not found Id: '.$this->_content_id,'Системная ошибка. Обратитесь к администратору');
		} else {
			$this->_data = $get_data[0];
		}
	}

	public function Make(){
        $this->_cashe_obj = array();
        
        $this->_results = array();
		  
        $get_result = $this->_top->_sql->exe("SELECT Answer_id FROM ".TAB_PREF."vote_answer c ".
            "where Vote_id=".$this->_content_id. " order by Sequence asc");
        
        for ($r=0;$r<count($get_result);$r++) {
            array_push($this->_results, $get_result[$r][0]); 
        }
//        Zend_Debug::dump($this->_results);
	}
	
	public function item($idx) {
		if ($this->_results===null) {
		  $this->Make();
		}
		return $this->getById($this->_results[$idx]);
	}	

	public function __get($param) {
        return $this->_data[$param];
	}

	public function __set($param, $value) {
        $value = $this->_top->Utils->prepareValueForSQL($value);
			
        $this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."vote SET $param='$value' WHERE vote_id={$this->_content_id}");
        $this->_data[$param] = $value;
        return true;	
	}

	public function add(){//добавить вариант ответа
        //определяем новый порядковый номер	
		$get_max_sequence = $this->_top->_sql->exe("SELECT IFNULL(MAX(sequence),0)+1 as s FROM ".TAB_PREF."vote_answer WHERE vote_id=".$this->_content_id);
		$max_sequence = count($get_max_sequence)==0 ? "0" : $get_max_sequence[0]['s'];
		
		//вставляем вариант вопроса
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."vote_answer(vote_id,sequence) VALUES($this->_content_id,$max_sequence);");
		$new_answer_id = $this->_top->_sql->last_insert_id();
		
		return $this->getById($new_answer_id);
	}
	
	public function getById($id) {//взять конкретный опрос по идешнику
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleVoteAnswer($this->_top, $this, $id);
		}
		
		return $this->_cashe_obj[$id];
	}
	
	public function length() { //кол-во вариантов ответов
        $get_data = $this->_top->_sql->exe("SELECT count(*) as c FROM ".TAB_PREF."vote_answer c where vote_id=".$this->_content_id);
		return $get_data[0]['c'];
	}	

	public function delete(){
	   $this->deleter();
	}
	
	protected function deleter() {//удаляем опрос	   
	   //идем по списку вариантов ответов и удаляем их и проголосовавших по ним
	   $this->Make();
	   $cnt = $this->length();
	   for($i = 0; $i < $cnt; $i++){
	       $a = $this->item($i);   
	       $a->delete();
	   }
        //удаляем сам опрос
        $this->_top->_sql->exeDummy("delete from ".TAB_PREF."vote where vote_id=".$this->_content_id);	
	}	
	
	public function checkIP($aIP){
	//возвращает true, если с этого IP уже голосовали
	   $sql = "select a.*  from ".TAB_PREF."vote_history a, ".TAB_PREF."vote b, ".TAB_PREF."vote_answer c ".
	       "where a.Answer_id=c.Answer_id and c.Vote_id=".$this->_content_id." and a.IP='$aIP'";
	   $d = $this->_top->_sql->exe($sql);
	   if( count($d) )
	       return true;
	   
	   return false;	
	}	
	
	public function addVote($aAnswer, $aIP){ //добавить голос
//	   echo "За $aAnswer проголосовал $aIP<br />";
	   $sql = "insert into ".TAB_PREF."vote_history(Answer_id, ip) values($aAnswer, '$aIP')";
	   $this->_top->_sql->exeDummy($sql);	
	}
}


class SingleVoteAnswer extends A_SingleContent {

	protected function loader() {
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."vote_answer WHERE answer_id={$this->_content_id}");
		if (count($get_data)==0) {
			throw $this->_top->Utils->PushError('VoteAnswer object not found Id: '.$this->_content_id,'Системная ошибка. Обратитесь к администратору');
		} else {
			$this->_data = $get_data[0];
		}
	}

	public function __get($param) {
	   if( $param == "votes"){ //кол-во проголосовавших за этот ответ
            $get_data = $this->_top->_sql->exe("SELECT count(*) as c FROM ".TAB_PREF."vote_history c where Answer_id=".$this->_content_id);
            return $get_data[0]['c'];
	   }
	   else 
	       return $this->_data[$param];
	}

	
	
	public function __set($param, $value) {
        if( $param == "Sequence" ){
            if( $this->Sequence > $value ){
                for($i=$value; $i<$this->Sequence; $i++){
                    $this->MoveUp();
                }
            }
            else{
                echo "Двигаем вниз<br />";
//                for($i = $this->Sequence; $i<$value; $i++)
                    $this->MoveDown();
            }        
        }
        else{
            $value = $this->_top->Utils->prepareValueForSQL($value);			
            $this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."vote_answer SET $param='$value' WHERE answer_id={$this->_content_id}");
            $this->_data[$param] = $value;
        }
        return true;
	}

	public function delete(){
	   $this->deleter();
	}
	
	protected function deleter() {
	   //удаляем проголосовавших
        $this->_top->_sql->exeDummy("delete from ".TAB_PREF."vote_history where answer_id=".$this->_content_id);
       //удаляем вариант ответа
        $this->_top->_sql->exeDummy("delete from ".TAB_PREF."vote_answer where answer_id=".$this->_content_id);
	}

	public function test(){
	   return $this->_parent->Question;
	}

	public function MoveUp(){
        $sql = "select * from ".TAB_PREF."vote_answer where vote_id = ".$this->_parent->Vote_id." and answer_id=".$this->_content_id;
        $curr_ord = $this->_top->_sql->exe($sql);
        $sql = "select * from ".TAB_PREF."vote_answer where vote_id=".$this->_parent->Vote_id." and Sequence < ".$curr_ord[0]['Sequence']." order by Sequence desc";
        $up_ord = $this->_top->_sql->exe($sql);
        if( !count($up_ord) ) //выше ничего нет
            return;
        //обновляем порядок у обоих
        $this->_top->_sql->exeDummy("update ".TAB_PREF."vote_answer set Sequence=".$curr_ord[0]["Sequence"]." where Answer_id=".$up_ord[0]["Answer_id"]);
        $this->_top->_sql->exeDummy("update ".TAB_PREF."vote_answer set Sequence=".$up_ord[0]["Sequence"]." where Answer_id=".$curr_ord[0]["Answer_id"]);
        //пересоздаем у родителя всякие кэши
//        $this->_parent->Make();
	}

	public function MoveDown(){
        $sql = "select * from ".TAB_PREF."vote_answer where vote_id = ".$this->_parent->Vote_id." and answer_id=".$this->_content_id;
        $curr_ord = $this->_top->_sql->exe($sql);
        $sql = "select * from ".TAB_PREF."vote_answer where vote_id=".$this->_parent->Vote_id." and Sequence > ".$curr_ord[0]['Sequence']." order by Sequence asc";
        $down_ord = $this->_top->_sql->exe($sql);
        if( !count($down_ord) )//ниже ничего нет
            return;
        //обновляем порядок у обоих
        $this->_top->_sql->exeDummy("update ".TAB_PREF."vote_answer set Sequence=".$curr_ord[0]["Sequence"]." where Answer_id=".$down_ord[0]["Answer_id"]);
        $this->_top->_sql->exeDummy("update ".TAB_PREF."vote_answer set Sequence=".$down_ord[0]["Sequence"]." where Answer_id=".$curr_ord[0]["Answer_id"]);
        //пересоздаем у родителя всякие кэши
//        $this->_parent->Make();
	}	
}